import { useEffect, useRef, useState } from 'react'
import SignatureCanvas from 'react-signature-canvas'
import { Button, Form, Input, Space, Popup, ImageUploader, Toast, Image, Switch } from 'antd-mobile'
import { checkRectifySave, checkTypeList } from '@api'
import { useParams, useNavigate } from 'react-router-dom'
import { formatDateTimeForInput } from '@utils/index'
import { uploadFileToOSS } from '@utils/upload'
import { getWatermark } from '@utils/index'

import './index.scss'

const maxCount = 9

function SignaturePad() {
    const { shopId } = useParams()
    const navigate = useNavigate()

    const sigCanvas = useRef({})
    const sigCanvas2 = useRef({})
    const [visible, setVisible] = useState(false)
    const [visible1, setVisible1] = useState(false)
    const [visible2, setVisible2] = useState(false)

    const [fileList, setFileList] = useState([])

    const [options, setOptions] = useState([])

    const [typeIndex, setTypeIndex] = useState([])

    const [checkTime, setCheckTime] = useState(formatDateTimeForInput())

    const [sign1, setSign1] = useState('')
    const [sign2, setSign2] = useState('')

    const [desc, setDesc] = useState('')

    const [record, setRecord] = useState([])

    const [details, setDetails] = useState({})

    const [rectifyRecords, setRectifyRecords] = useState([])

    const [showWatermark, setShowWatermark] = useState(false)
    const [watermark, setWatermark] = useState('')

    useEffect(() => {
        checkTypeList().then(({ success, data }) => {
            if (success && data) {
                setOptions(data)
            }
        })
        // 渲染数据
        const obj = JSON.parse(localStorage.getItem('merchantDetail') || '{}')
        setDetails(obj)
        const { checkTime: time, records, inspectedSign, inspectorsSign, checkTypeList: _checkTypeList } = JSON.parse(localStorage.getItem('checkItem') || '{}')
        setSign1(inspectorsSign)
        setSign2(inspectedSign)
        setRecord(records)
        setTypeIndex(_checkTypeList.map((e) => e.id))
        setCheckTime(formatDateTimeForInput(time))
    }, [])

    useEffect(() => {
        console.log(record)
    }, [record])

    const fileInputRef = useRef(null)
    const fileInputRef2 = useRef(null)

    const handleFileChange = (event) => {
        // 处理文件选择
        const file = event.target.files[0]
        uploadFileToOSS({ file }).then(({ res }) => {
            const url = res.requestUrls[0].split('?')[0]
            setSign1(url)
            clear(1)
            reset2()
        })
    }
    const handleFileChange2 = (event) => {
        // 处理文件选择
        const file = event.target.files[0]
        uploadFileToOSS({ file }).then(({ res }) => {
            const url = res.requestUrls[0].split('?')[0]
            setSign2(url)
            clear(2)
            reset2()
        })
    }

    const clear = (index) => {
        if (index === 1) {
            sigCanvas.current.clear()
        } else {
            sigCanvas2.current.clear()
        }
    }

    const save = (index) => {
        let image = ''
        if (index === 1) {
            image = sigCanvas.current.getTrimmedCanvas().toDataURL('image/png')
        } else {
            image = sigCanvas2.current.getTrimmedCanvas().toDataURL('image/png')
        }
        uploadFileToOSS({ file: image }).then(({ res }) => {
            const url = res.requestUrls[0].split('?')[0]
            if (index === 1) {
                setSign1(url)
            } else {
                setSign2(url)
            }
            clear(index)
            reset2()
        })
    }

    // 重置
    const reset = () => {
        setVisible(false)
        setFileList([])
        setDesc('')
    }

    const reset2 = () => {
        setVisible1(false)
        setVisible2(false)
    }

    // 提交
    const submit = () => {
        const { id } = JSON.parse(localStorage.getItem('checkItem') || '{}')
        let params = {
            verifyId: id,
            status: 'HAVING_RECTIFY',
            records: rectifyRecords
        }
        checkRectifySave(params).then(({ success, info }) => {
            Toast.show(info)
            if (success) {
                navigate(-1)
            }
        })
    }

    // 上传
    const upload = async (file) => {
        let result = null
        if (showWatermark) {
            result = await getWatermark(file, watermark)
        }
        const { res } = await uploadFileToOSS({ file: result || file })
        try {
            return { url: res.requestUrls[0].split('?')[0] }
        } catch (error) {
            throw new Error(error)
        }
    }

    // 添加记录
    const add = () => {
        setRectifyRecords((prev) => [...prev, { title: desc, imageList: fileList.map((e) => e.url) }])
        setVisible(false)
    }

    const del = (index) => {
        setRectifyRecords((prev) => prev.filter((_, idx) => idx !== index))
    }

    return (
        <div className="Add">
            <div className="Add_info">
                <div>
                    <p>单位：</p>
                    <p>{details.unit}</p>
                </div>
                <div>
                    <p>负责人：</p>
                    <p>{details.headName}</p>
                </div>
                <div>
                    <p>电话：</p>
                    <p>{details.headPhone}</p>
                </div>
                <div>
                    <p>行业类型：</p>
                    <p>{details.trade}</p>
                </div>
                <div>
                    <p>单位地址：</p>
                    <p>
                        {details.province}
                        {details.city}
                        {details.area}
                        {details.village}
                        {details.street}
                        {details.address}
                    </p>
                </div>
            </div>
            <Form>
                <Form.Item label="时间">
                    <Input type="datetime-local" value={checkTime} disabled />
                </Form.Item>
                <Form.Item label="检查类型">
                    <div className="Add_types">
                        {options.map((e) => (
                            <p key={e.id} className={typeIndex.includes(e.id) ? 'active' : ''}>
                                {e.name}
                            </p>
                        ))}
                    </div>
                </Form.Item>
            </Form>
            <div className="Add_box">
                <div className="Add_title">
                    <p>检查人员（签名）：</p>
                </div>
                {sign1 ? <Image className="sign_img" height={100} src={sign1} /> : null}
            </div>
            <div className="Add_box">
                <div className="Add_title">
                    <p>被检查单位负责人（签名）：</p>
                </div>
                {sign2 ? <Image className="sign_img" height={100} src={sign2} /> : null}
            </div>
            <div className="Add_list">
                <p>整改前：</p>
                {record.map((item, index) => (
                    <div className="Add_item" key={index}>
                        <div className="Add_item_text_box">
                            <p>
                                {index + 1}.{item.title}
                            </p>
                        </div>
                        <Space wrap>
                            {item.imageList.map((e, i) => (
                                <Image width={110} fit="cover" src={e} key={i} />
                            ))}
                        </Space>
                    </div>
                ))}
            </div>
            <div className="Add_list">
                <p>整改后：</p>
                {rectifyRecords.map((item, index) => (
                    <div className="Add_item" key={index}>
                        <div className="Add_item_text_box">
                            <p>
                                {index + 1}.{item.title}
                            </p>
                            <Button color="danger" size="mini" onClick={() => del(index)}>
                                删除
                            </Button>
                        </div>
                        <Space wrap>
                            {item.imageList.map((e, i) => (
                                <Image width={110} fit="cover" src={e} key={i} />
                            ))}
                        </Space>
                    </div>
                ))}
            </div>
            <div className="Add_btn">
                <Button color="primary" onClick={submit}>
                    保存
                </Button>
                <Button
                    color="warning"
                    onClick={() => {
                        reset()
                        setVisible(true)
                    }}
                >
                    添加整改记录
                </Button>
            </div>
            {/* 上传 */}
            <input type="file" style={{ display: 'none' }} ref={fileInputRef} onChange={handleFileChange} />
            <input type="file" style={{ display: 'none' }} ref={fileInputRef2} onChange={handleFileChange2} />
            {/* 签名 */}
            <Popup visible={visible1} onMaskClick={reset2} onClose={reset2} bodyStyle={{ height: '35vh' }}>
                <div className="sign_box">
                    <SignatureCanvas penColor="black" canvasProps={{ className: 'sigCanvas' }} ref={sigCanvas} />
                    <div className="sign_btns">
                        <Button color="primary" onClick={() => save(1)}>
                            保存
                        </Button>
                        <Button color="primary" onClick={() => clear(1)}>
                            重新签名
                        </Button>
                    </div>
                </div>
            </Popup>
            <Popup visible={visible2} onMaskClick={reset2} onClose={reset2} bodyStyle={{ height: '35vh' }}>
                <div className="sign_box">
                    <SignatureCanvas penColor="black" canvasProps={{ className: 'sigCanvas' }} ref={sigCanvas2} />
                    <div className="sign_btns">
                        <Button color="primary" onClick={() => save(2)}>
                            保存
                        </Button>
                        <Button color="primary" onClick={() => clear(2)}>
                            重新签名
                        </Button>
                    </div>
                </div>
            </Popup>
            {/* 添加违规记录 */}
            <Popup visible={visible} onMaskClick={reset} onClose={reset} bodyStyle={{ height: '70vh' }}>
                <div className="Add_upload_images">
                    <p>问题描述：</p>
                    <input value={desc} onChange={(e) => setDesc(e.target.value)} className="desc_inp" type="text" placeholder="请输入问题描述" />
                    <p>是否加水印：</p>
                    <Switch value={showWatermark} onChange={setShowWatermark} />
                    {showWatermark ? (
                        <>
                            <p>水印文案：</p>
                            <input value={watermark} onChange={(e) => setWatermark(e.target.value)} className="desc_inp" type="text" placeholder="请输入" />
                        </>
                    ) : null}
                    <p>问题图片：</p>
                    <ImageUploader
                        style={{ '--cell-size': '110px' }}
                        value={fileList}
                        multiple
                        upload={upload}
                        maxCount={maxCount}
                        showUpload={fileList.length < maxCount}
                        onChange={setFileList}
                        onCountExceed={(exceed) => {
                            Toast.show(`最多选择 ${maxCount} 张图片，你多选了 ${exceed} 张`)
                        }}
                    />
                    <Button color="primary" onClick={add}>
                        保存
                    </Button>
                </div>
            </Popup>
        </div>
    )
}

export default SignaturePad
